package merge

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func Merge(mergeArgs *MergeArgs) {
	filePath := mergeArgs.SourceHome
	outputFile := mergeArgs.OutputFile

	fileList, err := os.ReadDir(filePath)
	if err != nil {
		fmt.Println("读文件发生错误", err)
		return
	}

	var builder strings.Builder
	builder.WriteString("{")

	firstFile := true
	for _, file := range fileList {
		fileFullPath := filePath + string(os.PathSeparator) + file.Name()

		file0, err := os.Open(fileFullPath)
		if err != nil {
			fmt.Println(err)
			continue
		}
		if !firstFile {
			builder.WriteString(",")
		}
		firstFile = false

		dotIdx := strings.Index(file.Name(), ".")
		builder.WriteString(fmt.Sprintf("\n\"%s\":", file.Name()[:dotIdx]))
		scanner := bufio.NewScanner(file0)
		for scanner.Scan() {
			line := scanner.Text()
			builder.WriteString(strings.TrimSpace(line))
		}
	}
	builder.WriteString("\n}")

	opfile, err := os.OpenFile(outputFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("写文件发生错误", err)
		return
	}
	defer opfile.Close()
	opfile.WriteString(builder.String())
	fmt.Println("合并成功", opfile.Name())
}
